package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.client.utils.JSONUtils;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.Feign.ProductFeignService;
import com.atguigu.gulimall.cart.Interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.To.UserInfoTo;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.CartItemVo;
import com.atguigu.gulimall.cart.vo.CartVo;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;


    @Autowired
    ThreadPoolExecutor threadPoolExecutor;

    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOpts = getCartOpts();
        CartItemVo cartItemVo = new CartItemVo();


        String cartItmJSON =(String) cartOpts.get(skuId.toString());

        // 先判断之前购物车是否添加过数据
        if(StringUtils.isEmpty(cartItmJSON)){
            // 如果为空 就在redis中新添加数据
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                R info = productFeignService.info(skuId);
                SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItemVo.setSkuId(skuInfo.getSkuId());
                cartItemVo.setTitle(skuInfo.getSkuTitle());
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setPrice(skuInfo.getPrice());
                cartItemVo.setCount(num);
            }, threadPoolExecutor);


            CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
                // 查找 销售属性的集
                List<String> allSaleattrAsJson = productFeignService.getAllSaleattrAsJson(skuId);
                cartItemVo.setSkuAttrValues(allSaleattrAsJson);
            }, threadPoolExecutor);

           CompletableFuture.allOf(future,future1).get();
             // 序列化 购物项
            String cartItemJson = JSON.toJSONString(cartItemVo);
            cartOpts.put(skuId.toString(), cartItemJson);
            return cartItemVo;
        }else {
           // 如果从redis 从获取购物车的数据不为空  只需要 修改数量即可
            CartItemVo cartItemVo1 = JSON.parseObject(cartItmJSON, CartItemVo.class);
            cartItemVo1.setCount(cartItemVo1.getCount()+num);
            String toJSONString = JSON.toJSONString(cartItemVo1);
            cartOpts.put(skuId.toString(),toJSONString);
            return  cartItemVo1;
        }
    }


    @Override
    public CartItemVo getCart(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOpts = getCartOpts();
        String cartItemJson = (String) cartOpts.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(cartItemJson, CartItemVo.class);
        return cartItemVo;
    }


    /**
     * 获取购物车所有项信息
     * @return
     */
    @Override
    public CartVo getAllCartItem() throws ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        CartVo cartVo = new CartVo();


        // 先判断是否登录过 是取临时购物车还是 用户购物车
        if(userInfoTo.getUserId()!=null){
            // 先判断 临时购物车是否有数据 先看是否需要 先合并
            String tempCartKey=CartConstant.CART_PREFIX+userInfoTo.getUserKey();
            List<CartItemVo> cartDetail = getCartDetail(tempCartKey);
            if(cartDetail!=null&& cartDetail.size()!=0){
                for (CartItemVo item:cartDetail) {
                     addToCart(item.getSkuId(), item.getCount());
                }
            }
            // 合并成功 删除 临时购物车
            deleteTemporyCart(tempCartKey);
            String userCartKey=CartConstant.CART_PREFIX+userInfoTo.getUserId();
            List<CartItemVo> cartDetail1 = getCartDetail(userCartKey);
            cartVo.setItems(cartDetail1);
            return  cartVo;
        }else{
            // 获取临时购物车
            String tempCartKey=CartConstant.CART_PREFIX+userInfoTo.getUserKey();
            List<CartItemVo> cartItemVoList=getCartDetail(tempCartKey);
            cartVo.setItems(cartItemVoList);
            return  cartVo;
        }
    }

    @Override
    public List<CartItemVo> getItemsToOrderConfirm() {
       // 先判断是否登录
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()!=null){
            String cartKey = CartConstant.CART_PREFIX + userInfoTo.getUserId();
            List<CartItemVo> cartDetail = getCartDetail(cartKey);
            List<CartItemVo> collect = cartDetail.stream().filter(item -> item.getCheck()).map((item) -> {
               // 因为购物车中的数据是 redis中的 下订单时要要去查 真正的价格
                Long skuId = item.getSkuId();
                R currentPrice = productFeignService.getProductCurrentPrice(skuId);
                String data = (String) currentPrice.get("data");
                item.setPrice(new BigDecimal(data));
                return item;
            }).collect(Collectors.toList());

         return collect;
        } else{
            return null;
        }
    }

    private void deleteTemporyCart(String tempCartKey) {
      redisTemplate.delete(tempCartKey);
    }

    /**
     * 抽取方法  具体获取哪个购物车下的  购物项
     * @param cartKey  根据  购物车类型
     * @return
     */
    private List<CartItemVo> getCartDetail(String cartKey) {
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = boundHashOps.values();
        List<CartItemVo> collect = values.stream().map((obj) -> {
            String jsonCartItem = obj.toString();
            CartItemVo cartItemVo = JSON.parseObject(jsonCartItem, CartItemVo.class);
            return cartItemVo;
        }).collect(Collectors.toList());
            return  collect;
    }




    /**
     * 获取 购物车操作的绑定对象
     */
   private  BoundHashOperations<String, Object, Object>  getCartOpts(){
       UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
       String cartKey="";
       if(userInfoTo.getUserId()!=null){
           cartKey= CartConstant.CART_PREFIX+userInfoTo.getUserId();
       }else{
          //临时购物车
           cartKey= CartConstant.CART_PREFIX+userInfoTo.getUserKey();
       }
       BoundHashOperations<String, Object, Object> stringObjectObjectBoundHashOperations = redisTemplate.boundHashOps(cartKey);
       return stringObjectObjectBoundHashOperations;
   }


}
